use std::str::FromStr;

pub fn convert_base(num_str: &str, to_base: u32) -> String {
    let left = num_str.find("(").unwrap();
    let right = num_str.find(")").unwrap();
    let k = i32::from_str(&num_str[(left + 1)..right]).unwrap();

    let mut num = 0;
    for i in 0..left {
        num *= k;
        let cur = parse_digit(num_str.as_bytes()[i]);
        num += cur;
    }

    let mut bytes = vec![];
    while num > 0 {
        let m = num % to_base as i32;
        bytes.push(to_digit(m));
        num /= to_base as i32;
    }
    bytes.reverse();
    unsafe {
        String::from_utf8_unchecked(bytes)
    }
}

fn parse_digit(ch: u8) -> i32 {
    if ch.is_ascii_digit() {
        (ch - '0' as u8) as i32
    } else {
        (ch - 'a' as u8) as i32 + 10
    }
}

fn to_digit(digit: i32) -> u8 {
    if digit < 10 {
        digit as u8 + '0' as u8
    } else {
        (digit - 10) as u8 + 'a' as u8
    }
}

